/**
 *  作业【二选一】：
 *  实现如下函数：
 * @param {*} mode  表示路由模式，取值为hash和history。默认值是hash。
 * @param {*} routes  表示路由配置，是json数组。
 */
export function createRouter(mode = 'hash', routes) {
    //函数内部根据mode和routes完成不同路由模式的路由功能。
    switch (mode) {
        case 'hash':
            bindHashChange(routes)
            break
        case 'history':
            bindHistoryChange(routes)
            break
        default:
            bindHashChange(routes)
    }
}
/**
 * hash路由
 */
function bindHashChange(routes) {
    window.onload = function () {
        liClick()
        let hash = location.hash
        if (!hash) {
            location.hash = '#/home'
        }
        goPage()
    }

    window.onhashchange = function () {
        goPage()
    }

    function goPage() {
        let hash = location.hash // #/home
        let path = hash.slice(1)

        let route = routes.filter(item => item.path == path)
        if (route.length > 0) {
            document.querySelector('.content').innerHTML = route[0].component
        } else {
            console.log('没有匹配到路由')
        }
    }

    function liClick() {
        let liDoms = document.querySelectorAll('.footer li')

        for (let i = 0; i < liDoms.length; i++) {
            liDoms[i].onclick = function () {
                const path = this.getAttribute('path').slice(1)
                location.hash='#'+path
                goPage()
            }
        }
    }
}

/**
 * history
 */
function bindHistoryChange(routes) {
    window.onload = function () {
        initEvent()
    }

    window.onpopstate = function () {
        // 后退
        console.log('onpopstate')
        console.log('history.state', history.state)

        goPage(history.state?.path, false)
    }

    function initEvent() {
        liClick()
    }

    function liClick() {
        let liDoms = document.querySelectorAll('.footer li')

        for (let i = 0; i < liDoms.length; i++) {
            liDoms[i].onclick = function () {
                const path = this.getAttribute('path').slice(1)
                console.log(path);
                goPage(path)
            }
        }
    }

    function goPage(path, isSaveHistory = true) {
        let div = document.querySelector('.content')
        // 页面的替换（显示）
        const router = routes.find(route => route.path === path)
        div.innerHTML = router?.component
        // 记录历史记录
        isSaveHistory && history.pushState({ path }, '')
    }
}
